package com.An.controller;

import com.An.pojo.AdminUser;
import com.An.pojo.Student;
import com.An.pojo.StudentUser;
import com.An.service.LoginService;
import com.An.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @auther AnYang
 * @date 2022/3/26 22:29
 **/
@Controller
@RequestMapping("/user")
public class LoginController {
	@Autowired
	private LoginService loginService;
	@Autowired
	private HttpSession session;

	@PostMapping("/student")
	public String studentLogin(@RequestParam("username") String username, @RequestParam("pwd") String pwd, Model model, HttpServletRequest request) {
		StudentUser user = loginService.getUserByUserId(username);
		System.out.println(user);
		if (user != null) {
			String password = user.getPassword();
			if (MD5Utils.MD5(password).equals(pwd)) {
				Student student = loginService.getStudentBySno(user.sno);
				session.setAttribute("student", student);
				System.out.println("密码输入正确！");
				return "redirect:/homePage.html";
			} else {
				model.addAttribute("msg", "账号密码错误");
				return "student/login";
			}
		} else {
			model.addAttribute("msg", "账号密码错误");
			return "student/login";
		}
	}

	@RequestMapping(value = "/admin", method = RequestMethod.POST)
	//@ResponseBody
	public String login(@RequestParam("username") String username, @RequestParam("pwd") String pwd, Model model, HttpServletRequest request) {
		AdminUser user = loginService.getAdminUserByUsername(username);
		System.out.println(user);
		if (user != null) {
			String password = user.getPassword();
			if (MD5Utils.MD5(password).equals(pwd)) {
				session.setAttribute("user", user);
				System.out.println("密码输入正确！");
				return "redirect:/main.html";
			} else {
				model.addAttribute("msg", "账号密码错误");
				return "admin/login";
			}
		} else {
			model.addAttribute("msg", "账号密码错误");
			return "admin/login";
		}
	}

	@RequestMapping("/loginOut")
	public String loginOut(HttpSession session) {
		session.invalidate();//将session无效化，解绑任何与该session绑定的对象
		return "redirect:/index.html";
	}
}